package com.roy.minimq.namesrv.applicaton;

import com.roy.minimq.common.ThreadFactoryImpl;
import com.roy.minimq.common.namesrv.NamesrvConfig;
import com.roy.minimq.namesrv.infrastructure.RouteInfoManager;
import com.roy.minimq.namesrv.service.BrokerHousekeepingService;
import com.roy.minimq.namesrv.service.processor.DefaultRequestProcessor;
import com.roy.minimq.remoting.domain.entity.RemotingServer;
import com.roy.minimq.remoting.domain.nettyserver.NettyRemotingServer;
import com.roy.minimq.remoting.domain.nettyserver.NettyServerConfig;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ：楼兰
 * @date ：Created in 2021/8/9
 * @description:
 **/
public class NamesrvController {

    private RemotingServer remotingServer;
    private NettyServerConfig nettyServerConfig;
    private NamesrvConfig namesrvConfig;
    private RouteInfoManager routeInfoManager;
    private BrokerHousekeepingService BrokerHousekeepingService;
    private ExecutorService remotingExecutor;

    public NamesrvController(NamesrvConfig namesrvConfig,NettyServerConfig nettyServerConfig){
        this.namesrvConfig = namesrvConfig;
        this.nettyServerConfig = nettyServerConfig;
        this.routeInfoManager = new RouteInfoManager();
        this.BrokerHousekeepingService = new BrokerHousekeepingService(this);
    }

    //Netty服务端初始化
    public boolean initialize() {
        boolean result = true;
        this.remotingServer = new NettyRemotingServer(nettyServerConfig,this.BrokerHousekeepingService);
        this.remotingExecutor =
                Executors.newFixedThreadPool(nettyServerConfig.getServerWorkerThreads(), new ThreadFactoryImpl("RemotingExecutorThread_"));
        this.registerProcessor();
        return result;
    }

    private void registerProcessor() {
        this.remotingServer.registerDefaultProcessor(new DefaultRequestProcessor(this), this.remotingExecutor);
    }

    //Netty服务端启动
    public void start() {
        this.remotingServer.start();
    }

    //关闭NamesrvController
    public void shutdown() {
        this.remotingServer.shutdown();
    }

    public RouteInfoManager getRouteInfoManager() {
        return routeInfoManager;
    }
}
